// pages/setting/setting.js
const app = getApp();

Component({

  /**
   * 页面的初始数据
   */
  data: {
    setting: {}
  },

  observers: {
    'setting.**': function (setting) {
      // 存储到本地
      wx.setStorageSync('setting', JSON.stringify(setting));
      // 同步到app的setting数据中
      app.globalData.setting = setting;
    }
  },

  methods: {
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
      this.setData({
        setting: app.globalData.setting
      });
    },

    clearStorage () {
      wx.showModal({
        title: '操作提示',
        content: '清空缓存可能会导致数据丢失，请确认您的操作！',
        showCancel: true,
        success: (result) => {
          if(result.confirm){
            // 清除
            wx.clearStorage({
              success: function () {
                wx.showToast({
                  title: '清理成功！',
                  icon: 'success',
                });
              },
              fail: function () {
                wx.showToast({
                  title: '清理失败！',
                  icon: 'error',
                });
              }
            });
          }
        },
        fail: ()=>{},
        complete: ()=>{}
      });
    },

    handleSettingChange (e) {
      const value = e.detail.value;
      const key = `setting.${e.currentTarget.dataset.key}`;

      this.setData({
        [key]: value
      });
    }
  }
})